import java.io.*;
import java.net.*;
/*
 *  A class that listens to the port number and accepts
 *  requests from a java client (Applet).
 */
public class networkHandler {
	private String host;
	private int port;
	private Socket connection;
    private PrintWriter out;
    private BufferedReader in;
    
	public networkHandler(String host, int port) throws UnknownHostException, IOException {
		this.host = host;
		this.port = port;
        try {
            this.connection = new Socket(host, port);
            System.out.println("Connected to localhost in port "+port);
            out = new PrintWriter(this.connection.getOutputStream());
            out.flush();
            in = new BufferedReader(new InputStreamReader(this.connection.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host:"+host);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: "+host);
            System.exit(1);
        }
        System.out.println("done!");
	}
	
	/*
	 * Wait for the client to send us data.
     * NOTE: this class probably needs changing because
     * readline terminates a string when \n is encoountered.
	 */
	public String read() throws IOException {
        return in.readLine();
	}
	
	/*
	 * Send String formated message to client.
	 */
	public void send(String resp) {
        out.write(resp);
        out.flush(); 
	}
	
	/*
	 *  Close (safely) streams and sockets. 
	 */
	public void close() throws IOException {
        out.close();
        in.close();
        connection.close();
	}
}
